{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "#programming_fever\n",
    "#press s for sketch mode\n",
    "#press c for caroon mode\n",
    "#press ENTER for normal mode\n",
    "import cv2\n",
    "import numpy as np\n",
    "def cartoonize_image(img, ds_factor=4, sketch_mode=False):\n",
    "\n",
    "    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n",
    "    img_gray = cv2.medianBlur(img_gray, 7)\n",
    "\n",
    "    edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=5)\n",
    "    ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV)\n",
    "\n",
    "    if sketch_mode:\n",
    "        return cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)\n",
    "\n",
    "    img_small = cv2.resize(img, None, fx=1.0/ds_factor, fy=1.0/ds_factor , interpolation=cv2.INTER_AREA)\n",
    "    num_repetitions = 10\n",
    "    sigma_color = 5\n",
    "    sigma_space = 7\n",
    "    size = 5\n",
    "\n",
    "    for i in range(num_repetitions):\n",
    "        img_small = cv2.bilateralFilter(img_small, size, sigma_color, sigma_space)\n",
    "    img_output = cv2.resize(img_small, None, fx=ds_factor, fy=ds_factor, interpolation=cv2.INTER_LINEAR)\n",
    "    dst = np.zeros(img_gray.shape)\n",
    "    dst = cv2.bitwise_and(img_output, img_output, mask=mask)\n",
    "    return dst\n",
    "\n",
    "if __name__=='__main__':\n",
    "    cap = cv2.VideoCapture(0)\n",
    "    cur_char = -1\n",
    "    prev_char = -1\n",
    "    while True:\n",
    "        ret, frame = cap.read()\n",
    "        frame = cv2.resize(frame, None, fx=0.5, fy=0.5,interpolation=cv2.INTER_AREA)\n",
    "        c = cv2.waitKey(1)\n",
    "        if c == 27:\n",
    "            break\n",
    "        if c > -1 and c != prev_char:\n",
    "            cur_char = c\n",
    "        prev_char = c\n",
    "        if cur_char == ord('s'):\n",
    "            cv2.imshow('sketch mode', cartoonize_image(frame, sketch_mode=True))\n",
    "        elif cur_char == ord('c'):\n",
    "            cv2.imshow('Cartoon mode', cartoonize_image(frame, sketch_mode=False))\n",
    "        else:\n",
    "            cv2.imshow('normal mode', frame)\n",
    "    cap.release()\n",
    "    cv2.destroyAllWindows()\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
